package com.example.AIstudy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.AIstudy.DTO.LevelRecordDTO;
import com.example.AIstudy.domain.CompositionDetail;
import com.example.AIstudy.domain.LevelRecord;
import com.example.AIstudy.domain.TranslateDetail;
import com.example.AIstudy.domain.User;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.LevelRecordService;
import com.example.AIstudy.service.UserService;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@CrossOrigin
@RequestMapping("/levelRecord")
@Api(tags = "学习水平发展管理API")
public class LevelRecordController {

    @Autowired
    LevelRecordService levelRecordService;
    @Autowired
    UserService userService;
    //新增一个学生的学习周记录，这个接口需要先放着，因为这个能力水平需要很多条件来决定
    @ApiOperation("定时任务，每周一0点循环更新用户的学习周记录记录，如果用户在这周内什么都没做，则不会插入记录")
//    @Scheduled(cron="0 0 0 ? * MON")
    @GetMapping("/updateRecord")
    void insertLevelRecord() throws AIstudyException{
        List<Integer> ids=userService.getAllUserID();
        int size=ids.size();
        // 定义日期时间字符串的格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i=0;i<size;i++){
            try{
                //执行python的环境
                String anacondaUrl="python";
                String pythonapiURL=new File(".").getCanonicalPath()+"/features/"+"analyze_quiz_performance.py";
                String[]arg=new String[]{anacondaUrl, pythonapiURL,String.valueOf(ids.get(i))};
                Process proc = Runtime.getRuntime().exec(arg);
                int res = proc.waitFor();
                System.out.println(res);
                if (res == 0) {
                    System.out.println("成功执行");
                    //成功执行 获取输出信息
                    String line=null;
                    BufferedReader inData = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
                    StringBuilder builder=new StringBuilder();
                    while ((line = inData.readLine()) != null){
                        //直接返回建议信息的字符串
                            //如果是作文 需要将json文件转换为对象后 封装并返回
                            System.out.println(line);
                            Gson gson = new Gson();
                            LevelRecord record = gson.fromJson(line, LevelRecord.class);
                            record.setStuID(ids.get(i));
                            Date date = dateFormat.parse(record.getStartTimeStr());
                            // 将日期对象转换为 Timestamp 对象
                            //设置开始的时间和结束的时间
                            record.setStartTime(new Timestamp(date.getTime()));
                            date = dateFormat.parse(record.getEndTimeStr());
                            record.setEndTime(new Timestamp( date.getTime()));
                            levelRecordService.save(record);
                            //更新用户的综合水平
                        User user=userService.getUserByUserID(ids.get(i));
                        user.setOverlevel((int) (record.getOverlevel()*10));
                        userService.updateUserByID(user);
//                            inData.close();
                    }
                }else{
                    System.out.println("执行错误");
                    //未成功执行 获取错误输出信息
                    String line=null;
                    BufferedReader inError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "gb2312"));
                    while ((line = inError.readLine()) != null) {
                        System.out.println(line);
                        throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"智能分析错题失败");
                    }
                    inError.close();
                }
                proc.waitFor();
            }catch (IOException | InterruptedException |ParseException e){
                System.out.println(e.getMessage());
                throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"智能分析错题失败");
            }
        }
    }

    //分页获取学生的学习记录
    //这里限制只有学生本人才能查
    @ApiOperation("根据学生的id查询学习水平发展史，可以选择的条件为学习水平，起始时间，结束时间")
    @GetMapping("")
//    @PreAuthorize("hasAnyAuthority(#studentID.toString())")
    public IPage<LevelRecord> findUserByClassID(@ApiParam("学生ID")@RequestParam(value = "studentID") Integer studentID,
                                             @ApiParam("学习水平")@RequestParam(value = "level",required = false) Integer level,
                                             @ApiParam("起始时间")@RequestParam(value = "startTime",required = false) Timestamp startTime,
                                             @ApiParam("结束时间")@RequestParam(value = "endTime",required = false) Timestamp endTime,
                                             @ApiParam("页码")@RequestParam(defaultValue = "0")Integer pageNum,
                                             @ApiParam("每页记录数") @RequestParam(defaultValue = "10")Integer pageSize) {
        Map<String,Object> condition=new HashMap<>();
        condition.put("stuID",studentID);
        //教师的id只有在超级管理员登录的时候才为空
        if(level!=null) {
            condition.put("question",level);
        }
        if(startTime!=null) {
            condition.put("startTime",startTime);
        }
        if(endTime!=null) {
            condition.put("endTime",endTime);
        }
        return levelRecordService.findRecords(condition, pageNum,pageSize);
//        String datetimeStr = "2022-04-20 12:30:00"; // 这是一个示例日期时间字符串
//        // 定义日期时间字符串的格式
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = dateFormat.parse(datetimeStr);
//        // 将日期对象转换为 Timestamp 对象
//        Timestamp timestamp = new Timestamp(date.getTime());
//        System.out.println(timestamp);
//        return null;
    }
    @ApiOperation("根据学生的id查询学情分析")
    @GetMapping("/detail")
    public LevelRecordDTO findLevelRecordDetail(@ApiParam("学生ID")@RequestParam(value = "stuID") Integer stuID){
        return levelRecordService.findRecordDetail(stuID);
    }
}
